/** 
 
*/
import React, { PureComponent } from 'react';
import { PrimaryC, codeType, DATA_ENTRY, AdvancedSearch, ContentPackage, TableC } from '../../../comps';
import { message } from 'antd';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import ShareOptionModalC from './shareOptionModalC';
import config from '../../../comps/business/tradingMarket/config.js';
import MarketValueUploadC from './marketValueUploadC';
import { formSelectData } from '../../../utils/utils';

class ShareOptionManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      searchObj: { tradeStatus: ['0', '3'] },
      currentPage: 1,
      numInPage: 10,
      total: 0,
      optionStruct: [], //期权结构下拉
      optionStatus: [], //交易状态下拉
      columns: [],
      dataSource: [],
      exchangeCode: undefined,
      tradingCode: undefined,
      isReset: false, // 是否点击重置
      marketValueVisible: false, //市值上传弹窗
      sortItem: undefined, // 排序字段
      sortType: undefined, // 排序类型
      sortedInfo: null, //排序对象
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    const {
      globalM: {
        dataDictionary: { OTC_OPTION_BOOK_OPTIONSTRUCT = [], OTC_OPTION_TRADE_STATUS = [] },
      },
    } = this.props;
    this.setState({
      optionStruct: formSelectData(OTC_OPTION_BOOK_OPTIONSTRUCT), //期权结构
      optionStatus: formSelectData(OTC_OPTION_TRADE_STATUS), //交易状态
    });
    this.getShareData();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 查询期权列表数据
  getShareData = () => {
    const { searchObj, currentPage, numInPage } = this.state;

    this.props.dispatch({
      type: 'shareOptionManageM/queryOptionList',
      payload: {
        ...searchObj,
        currentPage: currentPage,
        numInPage: numInPage,
        sortItem: this.state.sortItem, // 排序字段
        sortType: this.state.sortType, // 排序类型
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            columns: data.columns || [],
            dataSource: data.dataSource || [],
            total: data.pageInfo?.total,
          });
        }
      },
    });
  };
  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
    });
  };
  // 新增按钮点击
  addClick = () => {
    //type（1-新增  2-复用 3-编辑）
    this.props.showShareOption(true, '1', undefined);
  };
  // 查询事件
  queryTableList = (e) => {
    let tempObj = {};
    for (let k in e) {
      if (k == 'tradeDate') {
        tempObj[k] = e[k].format('YYYYMMDD');
        continue;
      }
      if (k == 'exchangeCode') {
        continue;
      }
      if (k == 'underlying') {
        tempObj['exchangeCode'] = this.state.exchangeCode;
        tempObj['tradingCode'] = this.state.tradingCode;
        continue;
      }
      tempObj[k] = e[k];
    }
    this.setState(
      {
        searchObj: tempObj,
        isReset: false,
        currentPage: 1,
        numInPage: 10,
      },
      () => {
        this.getShareData();
      },
    );
  };
  // 复用按钮
  reUseOperate = (record) => {
    this.props.showShareOption(true, '2', record.bundleId);
  };
  // 编辑按钮
  editOperate = (record) => {
    this.props.showShareOption(true, '3', record.bundleId);
  };
  // 删除按钮
  deleteOperate = (record) => {
    this.props.dispatch({
      type: 'shareOptionManageM/deleteOptionByBookId',
      payload: {
        bundleId: record.bundleId,
      },
      callback: (type) => {
        if (type == 'success') {
          this.getShareData();
        }
      },
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination, filt, sorter) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    if (sorter) {
      if (sorter.order == 'descend') {
        // 降序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'descend', // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getShareData();
          },
        );
      } else if (sorter.order == 'ascend') {
        // 升序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'ascend', // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getShareData();
          },
        );
      } else {
        // 无序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.field, // 排序字段
            sortType: undefined, // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getShareData();
          },
        );
      }
    }
  };
  // 显示存款账号信息表格
  showTable = () => {
    const { currentPage, total, numInPage, columns, dataSource } = this.state;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo && JSON.stringify(sortedInfo) !== '{}' ? sortedInfo : {};
    columns.map((item) => {
      if (item.key !== 'operate') {
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
        item.width = 100;
      }

      if (item.key == 'productName' || item.key == 'underlying') {
        item.width = 180;
      }
      if (item.key == 'counterparty' || item.key == 'tradeDate' || item.key == 'expiryDate') {
        item.width = 120;
      }
    });
    //因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        title: '操作',
        width: '150px',
        // fixed:'right',
        operates: [
          {
            title: '复用',
            onClick: (record, index) => {
              this.reUseOperate(record);
            },
          },
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editOperate(record);
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteOperate(record);
            },
          },
        ],
      });
      columns.map((item) => {
        if (item.key == 'underlying') {
          item.render = (val, data) => {
            let exchange = config.filter((item) => {
              return item.value == data.exchangeCode;
            });
            return data.tradingCode + '-' + data.secuabbr + '-' + exchange[0]?.title;
          };
          item.width = 180;
        } else if (item.key == 'productName') {
          item.width = 180;
        } else if (item.key == 'counterparty' || item.key == 'tradeDate' || item.key == 'expiryDate') {
          item.width = 120;
        } else {
          item.width = 100;
        }
      });
    }
    return (
      <TableC
        columns={columns}
        loading={this.props.loading.effects['shareOptionManageM/queryOptionList'] == true}
        dataSource={dataSource}
        current={currentPage}
        total={total}
        pageSize={numInPage}
        rowKey='id'
        pagination={true}
        scroll={{ x: 'max-content' }}
        selfScrollY={true}
        onChange={this.handleTableChange}
      />
    );
  };
  // 簿记上传点击事件
  bookKeepClick = () => {
    this.setState({
      visible: true,
    });
  };
  //市值上传
  marketValueUpload = () => {
    this.setState({
      marketValueVisible: true,
    });
  };
  //子组件通知是否关闭弹窗
  marketValueVisibleChange = (flag) => {
    this.setState({
      marketValueVisible: flag,
    });
  };
  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'product',
          title: '产品名称',
          type: DATA_ENTRY.PRODUCTLIST,
          allowClear: true,
          maxTagCount: 0,
          dataType: 2,
          multiple: true,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //只有簿记和指令模式产品
        },
        {
          dataIndex: 'optionStruct',
          title: '期权结构',
          type: DATA_ENTRY.SELECT,
          isMultiple: true,
          dataSource: this.state.optionStruct,
          maxTagCount: 0,
          allowClear: true,
        },
        {
          dataIndex: 'tradeDate',
          title: '交易日期',
          type: DATA_ENTRY.SINGLEDATE,
        },
        {
          dataIndex: 'underlying',
          title: '标的证券',
          type: DATA_ENTRY.SECURITIESCODE,
          codeType: codeType.cwqq,
          allowClear: true,
          onChange: (e) => {
            if (e) {
              this.setState({
                tradingCode: e.tradingCode,
                exchangeCode: e.exchangeCode,
              });
            }
          },
        },
        {
          dataIndex: 'counterPartyId',
          title: '交易对手',
          type: DATA_ENTRY.TRADINGCOMPANY,
          dataType: 2,
          isOtc: '1',
          allowClear: true,
        },
        {
          dataIndex: 'tradeStatus',
          title: '交易状态',
          type: DATA_ENTRY.SELECT,
          dataSource: this.state.optionStatus,
          allowClear: true,
          isMultiple: true,
          maxTagCount: 0,
          initialValue: ['0', '3'],
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='期权管理'
        contentHtml={
          <div>
            <div style={{ marginBottom: '10px' }}>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC title='新增' style={{ margin: '10px 10px 10px 0px' }} onClick={this.addClick} />
            <PrimaryC title='簿记上传' style={{ margin: ' 10px 0px' }} onClick={this.bookKeepClick} />
            <PrimaryC title='市值上传' style={{ margin: '10px' }} onClick={this.marketValueUpload} />
            <div>{this.showTable()}</div>
            {this.state.visible ? <ShareOptionModalC visible={this.state.visible} changeVisible={this.changeVisible} /> : null}
            {this.state.marketValueVisible && <MarketValueUploadC visible={this.state.marketValueVisible} changeVisible={this.marketValueVisibleChange} />}
          </div>
        }
      />
    );
  }
}
export default connect(({ shareOptionManageM, bookM, loading, globalM }) => ({
  shareOptionManageM,
  bookM,
  loading,
  globalM,
}))(ShareOptionManage);
